package com.bluesky.jwf.component.tree;

import com.bluesky.jwf.ComponentFactory;
import com.bluesky.jwf.component.list.ListItem;
import com.bluesky.jwf.component.list.ListView;

/**
 * this tree view actually is a list view. tree node indents by the depth.
 * 
 * @author hz00260
 * 
 */
public class TreeView extends ListView {

	protected TreeNodeNavigator navigator;

	public TreeView() {

	}

	public TreeNodeNavigator getNavigator() {
		return navigator;
	}

	public void setNavigator(TreeNodeNavigator navigator) {
		this.navigator = navigator;
	}

	@Override
	public void dataBind() {
		listItems.clear();

		ListItem listItem = (ListItem) ComponentFactory.getInstance()
				.createComponent(itemClass.getName(), itemTag.toHtml());

		listItem.setListView(this);
		listItem.setIndex(0);
		listItem.setModel(model);

		listItems.add(listItem);

		updateView();
	}

	public void expand(TreeViewItem item) {

		int index = listItems.indexOf(item);
		int i = 0;
		for (Object o : navigator.getChildren(item.getModel())) {
			ListItem listItem = (ListItem) ComponentFactory.getInstance()
					.createComponent(itemClass.getName(), itemTag.toHtml());

			listItem.setListView(this);
			listItem.setIndex(0);
			listItem.setModel(o);

			// insert after the parent item
			listItems.add(index + i + 1, listItem);

			i++;
		}

		item.setExpanded(true);

		updateView();
	}

	/**
	 * remove child items
	 * 
	 * @param item
	 */
	public void collapse(TreeViewItem item) {

		int index = listItems.indexOf(item);

		while (listItems.size() > index + 1) {
			ListItem li = listItems.get(index + 1);
			if (!navigator.isAncestor(li.getModel(), item.getModel()))
				break;

			listItems.remove(li);

		}
		item.setExpanded(false);

		updateView();
	}

}
